import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

/// 简化的加密工具类
/// 注意：这是演示版本，生产环境请使用专业的加密库
class CryptoUtil {
  static const String secretKey = "3cb64895b99444ca935a0b3db8307b58";
  
  /// 生成密钥字节数组（与Go服务端兼容）
  static Uint8List _generateKey(String key) {
    // 与Go服务端使用相同的密钥生成方式
    final keyBytes = Uint8List(32);
    final keyString = utf8.encode(key);
    for (int i = 0; i < 32; i++) {
      keyBytes[i] = keyString[i % keyString.length];
    }
    return keyBytes;
  }
  
  /// 简化的加密方法
  /// 注意：这只是演示，实际项目中请使用AES-GCM等安全算法
  static String encrypt(String plaintext) {
    try {
      final plaintextBytes = utf8.encode(plaintext);
      final keyBytes = _generateKey(secretKey);
      final random = Random();
      
      // 生成随机IV
      final iv = Uint8List(16);
      for (int i = 0; i < 16; i++) {
        iv[i] = random.nextInt(256);
      }
      
      // 简单的XOR加密（仅用于演示）
      final encryptedBytes = Uint8List(plaintextBytes.length);
      for (int i = 0; i < plaintextBytes.length; i++) {
        encryptedBytes[i] = plaintextBytes[i] ^ keyBytes[i % keyBytes.length] ^ iv[i % iv.length];
      }
      
      // 将IV和密文组合
      final combinedBytes = Uint8List(16 + encryptedBytes.length);
      combinedBytes.setRange(0, 16, iv);
      combinedBytes.setRange(16, 16 + encryptedBytes.length, encryptedBytes);
      
      return base64.encode(combinedBytes);
    } catch (e) {
      throw Exception('Encryption failed: $e');
    }
  }
  
  /// 简化的解密方法
  static String decrypt(String ciphertext) {
    try {
      final combinedBytes = base64.decode(ciphertext);
      
      if (combinedBytes.length < 16) {
        throw Exception('Invalid ciphertext length');
      }
      
      final iv = combinedBytes.sublist(0, 16);
      final encryptedBytes = combinedBytes.sublist(16);
      final keyBytes = _generateKey(secretKey);
      
      // 简单的XOR解密
      final decryptedBytes = Uint8List(encryptedBytes.length);
      for (int i = 0; i < encryptedBytes.length; i++) {
        decryptedBytes[i] = encryptedBytes[i] ^ keyBytes[i % keyBytes.length] ^ iv[i % iv.length];
      }
      
      return utf8.decode(decryptedBytes);
    } catch (e) {
      throw Exception('Decryption failed: $e');
    }
  }
}
